<template>
  <div class="home-container">
    <el-row :gutter="20">
      <!-- 左侧输入区域 -->
      <el-col :span="10">
        <el-card class="input-card">
          <template #header>
            <div class="card-header">
              <el-icon><Edit /></el-icon>
              <span>装修需求输入</span>
            </div>
          </template>
          
          <el-form
            ref="formRef"
            :model="form"
            :rules="rules"
            label-width="100px"
            class="decoration-form"
          >
            <!-- 户型图上传 -->
            <el-form-item label="户型图" prop="floorPlan">
              <div class="upload-section">
                <el-upload
                  ref="uploadRef"
                  :auto-upload="false"
                  :on-change="handleFileChange"
                  :before-upload="beforeUpload"
                  :show-file-list="false"
                  accept="image/*"
                  drag
                >
                  <div class="upload-content">
                    <el-icon v-if="!uploadedFile" class="upload-icon"><Plus /></el-icon>
                    <div v-if="!uploadedFile" class="upload-text">
                      <p>点击或拖拽上传户型图</p>
                      <p class="upload-tip">支持 PNG、JPG、JPEG、BMP 格式</p>
                    </div>
                    <div v-else class="uploaded-file">
                      <el-icon><Picture /></el-icon>
                      <span>{{ uploadedFile.original_filename }}</span>
                      <el-button type="text" @click="removeFile">删除</el-button>
                    </div>
                  </div>
                </el-upload>
              </div>
            </el-form-item>

            <!-- 装修风格 -->
            <el-form-item label="装修风格" prop="decorationStyle">
              <el-select
                v-model="form.decorationStyle"
                placeholder="请选择装修风格"
                style="width: 100%"
              >
                <el-option
                  v-for="style in decorationStyles"
                  :key="style"
                  :label="style"
                  :value="style"
                />
              </el-select>
            </el-form-item>

            <!-- 房间类型 -->
            <el-form-item label="房间类型" prop="roomType">
              <el-select
                v-model="form.roomType"
                placeholder="请选择房间类型"
                style="width: 100%"
              >
                <el-option
                  v-for="type in roomTypes"
                  :key="type"
                  :label="type"
                  :value="type"
                />
              </el-select>
            </el-form-item>

            <!-- 预算范围 -->
            <el-form-item label="预算范围" prop="budget">
              <el-row :gutter="10">
                <el-col :span="12">
                  <el-input-number
                    v-model="form.budgetMin"
                    :min="0"
                    :max="1000"
                    placeholder="最低预算"
                    style="width: 100%"
                  />
                </el-col>
                <el-col :span="12">
                  <el-input-number
                    v-model="form.budgetMax"
                    :min="0"
                    :max="1000"
                    placeholder="最高预算"
                    style="width: 100%"
                  />
                </el-col>
              </el-row>
              <div class="budget-tip">单位：万元</div>
            </el-form-item>

            <!-- 装修需求描述 -->
            <el-form-item label="需求描述" prop="decorationPlan">
              <el-input
                v-model="form.decorationPlan"
                type="textarea"
                :rows="4"
                placeholder="请详细描述您的装修需求，包括功能要求、喜好颜色、家庭成员情况等..."
                maxlength="1000"
                show-word-limit
              />
            </el-form-item>

            <!-- 提交按钮 -->
            <el-form-item>
              <el-button
                type="primary"
                size="large"
                :loading="loading"
                :disabled="isGenerating"
                @click="handleSubmit"
                style="width: 100%"
              >
                <el-icon v-if="!loading"><MagicStick /></el-icon>
                {{ isGenerating ? '正在生成中...' : '生成装修方案' }}
              </el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </el-col>

      <!-- 右侧结果显示区域 -->
      <el-col :span="14">
        <el-card class="result-card">
          <template #header>
            <div class="card-header">
              <el-icon><Document /></el-icon>
              <span>设计方案结果</span>
              <div class="header-actions">
                <span v-if="statusValue" style="margin-right:8px;color:#909399;font-size:12px">状态：{{ statusValue }}</span>
                <el-button
                  v-if="statusValue === 'processing' || statusValue === 'pending'"
                  type="primary"
                  size="small"
                  @click="checkStatus"
                >
                  刷新状态
                </el-button>
              </div>
            </div>
          </template>

          <div class="result-content">
            <!-- 加载状态 -->
            <div v-if="statusValue === 'processing' || statusValue === 'pending'" class="loading-section">
              <el-result
                icon="loading"
                title="正在生成装修方案"
                sub-title="AI正在分析您的需求，请稍候..."
              >
                <template #extra>
                  <el-progress
                    :percentage="progress"
                    :status="progress === 100 ? 'success' : undefined"
                  />
                  <p class="progress-text">{{ progressText }}</p>
                </template>
              </el-result>
            </div>

            <!-- 结果显示 -->
            <div v-else-if="statusValue === 'completed'" class="result-section">
              <div v-if="currentRequest.result" class="analysis-result">
                <h3><el-icon><House /></el-icon> 户型分析结果</h3>
                <div class="result-text" v-html="formatResult(currentRequest.result)"></div>
              </div>

              <div v-if="currentRequest.generated_images?.length" class="images-section">
                <h3><el-icon><Picture /></el-icon> 生成的装修改造效果图</h3>
                <el-row :gutter="20">
                  <el-col
                    v-for="(imageUrl, index) in currentRequest.generated_images"
                    :key="index"
                    :span="12"
                    class="image-item"
                  >
                    <el-card class="image-card" shadow="hover">
                      <img
                        :src="imageUrl"
                        :alt="`效果图 ${index + 1}`"
                        class="result-image"
                        @click="previewImage(imageUrl)"
                      />
                      <div class="image-overlay">
                        <el-button type="primary" size="small" @click="previewImage(imageUrl)">
                          <el-icon><ZoomIn /></el-icon>
                          预览
                        </el-button>
                        <el-button type="success" size="small" @click="downloadImage(imageUrl, index)">
                          <el-icon><Download /></el-icon>
                          下载
                        </el-button>
                      </div>
                    </el-card>
                  </el-col>
                </el-row>
              </div>
            </div>

            <!-- 错误状态 -->
            <div v-else-if="statusValue === 'failed'" class="error-section">
              <el-result
                icon="error"
                title="生成失败"
                :sub-title="currentRequest.error || '生成装修方案时发生错误'"
              >
                <template #extra>
                  <el-button type="primary" @click="resetForm">重新生成</el-button>
                </template>
              </el-result>
            </div>

            <!-- 默认状态 -->
            <div v-else class="default-section">
              <el-empty description="请填写装修需求并上传户型图，然后点击生成装修方案">
                <el-icon size="60"><House /></el-icon>
              </el-empty>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 图片预览对话框 -->
    <el-dialog v-model="previewVisible" title="图片预览" width="80%">
      <div class="preview-container">
        <img :src="previewImageUrl" alt="预览图片" class="preview-image" />
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, onBeforeUnmount, computed, watch } from 'vue'
import { storeToRefs } from 'pinia'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useDecorationStore } from '@/stores/decoration'
import { Edit, Plus, Picture, MagicStick, Document, House, ZoomIn, Download } from '@element-plus/icons-vue'

const decorationStore = useDecorationStore()

// 响应式数据
const formRef = ref()
const uploadRef = ref()
const uploadedFile = ref(null)
const previewVisible = ref(false)
const previewImageUrl = ref('')
const progress = ref(0)
const progressText = ref('准备中...')
const pollingTimer = ref(null)
const pollingRequestId = ref(null)
const STORAGE_KEY_ID = 'decoration_request_id'
const STORAGE_KEY_DATA = 'decoration_current_request'
const STORAGE_KEY_FORM = 'decoration_form_data'
const STORAGE_KEY_FILE = 'decoration_uploaded_file'

// 表单数据
const form = reactive({
  decorationStyle: '',
  roomType: '',
  decorationPlan: '',
  budgetMin: 10,
  budgetMax: 50
})

// 持久化: 监听表单变化与已上传文件变化
watch(
  () => ({
    decorationStyle: form.decorationStyle,
    roomType: form.roomType,
    decorationPlan: form.decorationPlan,
    budgetMin: form.budgetMin,
    budgetMax: form.budgetMax
  }),
  (val) => {
    try {
      localStorage.setItem(STORAGE_KEY_FORM, JSON.stringify(val))
    } catch {}
  },
  { deep: true }
)

watch(
  uploadedFile,
  (file) => {
    try {
      if (file) {
        // 仅保存必要字段
        const minimal = {
          original_filename: file.original_filename,
          oss_url: file.oss_url
        }
        localStorage.setItem(STORAGE_KEY_FILE, JSON.stringify(minimal))
      } else {
        localStorage.removeItem(STORAGE_KEY_FILE)
      }
    } catch {}
  },
  { deep: false }
)

// 表单验证规则
const rules = {
  decorationStyle: [
    { required: true, message: '请选择装修风格', trigger: 'change' }
  ],
  roomType: [
    { required: true, message: '请选择房间类型', trigger: 'change' }
  ],
  decorationPlan: [
    { required: true, message: '请填写装修需求描述', trigger: 'blur' },
    { min: 10, message: '需求描述至少10个字符', trigger: 'blur' }
  ]
}

// 计算属性（使用 storeToRefs 避免“ref 包 ref”导致的状态不更新）
const { decorationStyles, roomTypes, loading, isGenerating, currentRequest } = storeToRefs(decorationStore)
const statusValue = computed(() => currentRequest.value?.status || '')

// 监听生成状态变化
watch(isGenerating, (newVal) => {
  if (newVal) {
    startProgress()
    startPolling()
  }
})

// 方法
const handleFileChange = async (file) => {
  try {
    const result = await decorationStore.uploadFile(file.raw)
    uploadedFile.value = result.file
    ElMessage.success('文件上传成功')
  } catch (error) {
    ElMessage.error(error.message || '文件上传失败')
  }
}

const beforeUpload = (file) => {
  const isImage = file.type.startsWith('image/')
  const isLt10M = file.size / 1024 / 1024 < 10

  if (!isImage) {
    ElMessage.error('只能上传图片文件!')
    return false
  }
  if (!isLt10M) {
    ElMessage.error('图片大小不能超过 10MB!')
    return false
  }
  return false // 阻止自动上传
}

const removeFile = () => {
  uploadedFile.value = null
  uploadRef.value.clearFiles()
  try {
    localStorage.removeItem(STORAGE_KEY_FILE)
  } catch {}
}

const handleSubmit = async () => {
  try {
    await formRef.value.validate()
    
    if (!uploadedFile.value) {
      ElMessage.warning('请先上传户型图')
      return
    }

    const formData = {
      // 驼峰（兼容旧逻辑）
      decorationStyle: form.decorationStyle,
      roomType: form.roomType,
      decorationPlan: form.decorationPlan,
      budgetMin: form.budgetMin,
      budgetMax: form.budgetMax,
      floorPlanUrl: uploadedFile.value.oss_url,
      // 下划线（后端要求）
      decoration_style: form.decorationStyle,
      room_type: form.roomType,
      decoration_plan: form.decorationPlan,
      budget_min: form.budgetMin,
      budget_max: form.budgetMax,
      floor_plan_url: uploadedFile.value.oss_url
    }

    const res = await decorationStore.generatePlan(formData)
    ElMessage.success('装修方案生成请求已提交')

    // 立即启动进度与轮询，绑定当前 requestId
    const newId = currentRequest.value?.id || res?.request_id
    startProgress()
    startPolling(newId)

    // 持久化 request_id，防止刷新后丢失
    try {
      localStorage.setItem(STORAGE_KEY_ID, String(newId || ''))
    } catch {}
  } catch (error) {
    ElMessage.error(error.message || '提交失败')
  }
}

const checkStatus = async (specificId) => {
  const id = specificId || currentRequest.value?.id || pollingRequestId.value
  if (!id) return
  
  try {
    await decorationStore.checkRequestStatus(Number(id))
    
    if (currentRequest.value.status === 'completed') {
      progress.value = 100
      progressText.value = '生成完成!'
      ElMessage.success('装修方案生成完成!')
      stopPolling()
    } else if (currentRequest.value.status === 'failed') {
      ElMessage.error('装修方案生成失败')
      stopPolling()
    } 
    // 持久化当前状态，刷新可恢复
    try {
      localStorage.setItem(STORAGE_KEY_DATA, JSON.stringify(currentRequest.value || {}))
      localStorage.setItem(STORAGE_KEY_ID, String(currentRequest.value?.id || id || ''))
    } catch {}
  } catch (error) {
    ElMessage.error('获取状态失败')
  }
}

const startPolling = (id) => {
  stopPolling()
  if (id) pollingRequestId.value = id
  const targetId = id || currentRequest.value?.id || pollingRequestId.value
  if (!targetId) return
  pollingTimer.value = setInterval(() => {
    checkStatus(targetId)
  }, 3000)
}

const stopPolling = () => {
  if (pollingTimer.value) {
    clearInterval(pollingTimer.value)
    pollingTimer.value = null
  }
}

const startProgress = () => {
  progress.value = 0
  progressText.value = '准备中...'
  
  const interval = setInterval(() => {
    if (progress.value < 90) {
      progress.value += Math.random() * 10
      if (progress.value < 30) {
        progressText.value = '分析户型图...'
      } else if (progress.value < 60) {
        progressText.value = '生成设计方案...'
      } else {
        progressText.value = '优化设计细节...'
      }
    }
  }, 1000)

  // 5秒后清除定时器
  setTimeout(() => {
    clearInterval(interval)
  }, 5000)
}

const sanitizeText = (raw) => {
  if (!raw) return ''
  let text = String(raw)
  // 移除所有 URL（不向用户暴露外部链接）
  text = text.replace(/https?:\/\/[^\s]+/g, '')
  // 去掉“您的装修效果是：[...]”这类包含图片链接的段落
  try {
    text = text.replace(/您的装修效果是：\s*\[[\s\S]*?\]/g, '')
  } catch {}
  // 规范多余空格
  text = text.replace(/\s{2,}/g, ' ').trim()
  return text
}

const formatResult = (result) => {
  // 纯文本
  if (typeof result === 'string') {
    return sanitizeText(result).replace(/\n/g, '<br>')
  }

  // 常规 output 字段
  if (result && result.output) {
    return sanitizeText(result.output).replace(/\n/g, '<br>')
  }

  // Coze 工作流返回里，result.data 可能是一个被转义的 JSON 字符串
  if (result && typeof result.data === 'string') {
    try {
      const nested = JSON.parse(result.data)
      const text = nested.data || nested.output || result.data
      return sanitizeText(text).replace(/\n/g, '<br>')
    } catch (e) {
      return sanitizeText(result.data).replace(/\n/g, '<br>')
    }
  }

  // 兜底：对象里直接有 data.text
  if (result && result.data && typeof result.data === 'object') {
    const text = result.data.data || result.data.output || JSON.stringify(result.data)
    return sanitizeText(text).replace(/\n/g, '<br>')
  }

  return JSON.stringify(result, null, 2)
}

const previewImage = (url) => {
  previewImageUrl.value = url
  previewVisible.value = true
}

const downloadImage = (url, index) => {
  const link = document.createElement('a')
  link.href = url
  link.download = `装修效果图_${index + 1}.jpg`
  link.click()
}

const resetForm = () => {
  decorationStore.resetCurrentRequest()
  progress.value = 0
  progressText.value = '准备中...'
}

// 生命周期
onMounted(async () => {
  try {
    await Promise.all([
      decorationStore.fetchStyles(),
      decorationStore.fetchRoomTypes()
    ])
  } catch (error) {
    ElMessage.error('初始化数据失败')
  }
  // 恢复左侧表单与上传文件
  try {
    const savedForm = localStorage.getItem(STORAGE_KEY_FORM)
    if (savedForm) {
      const parsed = JSON.parse(savedForm)
      form.decorationStyle = parsed.decorationStyle || ''
      form.roomType = parsed.roomType || ''
      form.decorationPlan = parsed.decorationPlan || ''
      form.budgetMin = typeof parsed.budgetMin === 'number' ? parsed.budgetMin : 10
      form.budgetMax = typeof parsed.budgetMax === 'number' ? parsed.budgetMax : 50
    }
  } catch {}
  try {
    const savedFile = localStorage.getItem(STORAGE_KEY_FILE)
    if (savedFile) {
      const parsed = JSON.parse(savedFile)
      if (parsed && parsed.oss_url) {
        uploadedFile.value = parsed
      }
    }
  } catch {}
  // 刷新后恢复上次的 request（优先使用完整数据）
  try {
    const savedData = localStorage.getItem(STORAGE_KEY_DATA)
    if (savedData) {
      const parsed = JSON.parse(savedData)
      if (parsed && parsed.id) {
        decorationStore.currentRequest = parsed
        pollingRequestId.value = parsed.id
        if (parsed.status === 'processing' || parsed.status === 'pending') {
          startPolling(parsed.id)
        }
      }
    } else {
      const savedId = localStorage.getItem(STORAGE_KEY_ID)
      if (savedId) {
        pollingRequestId.value = Number(savedId)
        await decorationStore.checkRequestStatus(Number(savedId))
        if (currentRequest.value?.status === 'processing' || currentRequest.value?.status === 'pending') {
          startPolling(Number(savedId))
        }
      }
    }
  } catch {}
})

onBeforeUnmount(() => {
  stopPolling()
})
</script>

<style scoped>
.home-container {
  max-width: 1400px;
  margin: 0 auto;
}

.input-card,
.result-card {
  height: calc(100vh - 200px);
  overflow-y: auto;
}

.card-header {
  display: flex;
  align-items: center;
  gap: 8px;
  font-weight: 600;
}

.header-actions {
  margin-left: auto;
}

.decoration-form {
  padding: 20px 0;
}

.upload-section {
  width: 100%;
}

.upload-content {
  text-align: center;
  padding: 20px;
}

.upload-icon {
  font-size: 48px;
  color: #c0c4cc;
  margin-bottom: 16px;
}

.upload-text p {
  margin: 8px 0;
  color: #606266;
}

.upload-tip {
  font-size: 12px;
  color: #909399;
}

.uploaded-file {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  padding: 10px;
  background-color: #f0f9ff;
  border: 1px solid #b3d8ff;
  border-radius: 4px;
}

.budget-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 4px;
}

.result-content {
  height: 100%;
  overflow-y: auto;
}

.loading-section,
.result-section,
.error-section,
.default-section {
  height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: center;
}

.progress-text {
  margin-top: 16px;
  color: #606266;
}

.analysis-result {
  margin-bottom: 30px;
}

.analysis-result h3 {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 16px;
  color: #303133;
}

.result-text {
  background-color: #f8f9fa;
  padding: 16px;
  border-radius: 6px;
  border-left: 4px solid #409eff;
  line-height: 1.6;
}

.images-section h3 {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 20px;
  color: #303133;
}

.image-item {
  margin-bottom: 20px;
}

.image-card {
  position: relative;
  overflow: hidden;
}

.result-image {
  width: 100%;
  height: 200px;
  object-fit: cover;
  cursor: pointer;
  transition: transform 0.3s;
}

.result-image:hover {
  transform: scale(1.05);
}

.image-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 10px;
  opacity: 0;
  transition: opacity 0.3s;
}

.image-card:hover .image-overlay {
  opacity: 1;
}

.preview-container {
  text-align: center;
}

.preview-image {
  max-width: 100%;
  max-height: 70vh;
  object-fit: contain;
}

/* 滚动条样式 */
::-webkit-scrollbar {
  width: 6px;
}

::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 3px;
}

::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 3px;
}

::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}
</style>
